package com.haixiaoke.saas.enterprise.workOrder.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.WorkOrderConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.workOrder.domain.WorkOrder;
import com.haixiaoke.saas.workOrder.domain.WorkOrderRecord;
import com.haixiaoke.saas.workOrder.service.IWorkOrderRecordService;
import com.haixiaoke.saas.workOrder.service.IWorkOrderService;
import com.haixiaoke.saas.system.BaseController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 工单Controller
 *
 * @author panda
 * @date 2024-09-02
 */
@RestController
@RequestMapping("/enterprise/workOrder/workOrder")
public class EnterpriseWorkOrderController extends BaseController {
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IWorkOrderRecordService workOrderRecordService;

    /**
     * 工单管理--查询工单列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:list')")
    @GetMapping("/list")
    @TenantScope
    public TableDataInfo list(WorkOrder workOrder) {
        startPage();
        workOrder.setTenantId(TenantContext.getTenantId());
        List<WorkOrder> list = workOrderService.selectWorkOrderList(workOrder);
        return getDataTable(list);
    }

    /**
     * 工单人员管理--查询工单列表
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:listByPerson')," +
            "@ss.bizHasAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @GetMapping("/list/byPerson")
    @TenantScope
    public TableDataInfo listByMaintenance(WorkOrder workOrder) {
        startPage();
        workOrder.setTenantId(TenantContext.getTenantId());
        workOrder.setBusUserId(getUserId());
        List<WorkOrder> list = workOrderService.selectWorkOrderList(workOrder);
        return getDataTable(list);
    }

    /**
     * 统计工单状态数量
     */
    @GetMapping("/countState")
    @TenantScope
    public AjaxResult countState(WorkOrder workOrder) {
        workOrder.setTenantId(TenantContext.getTenantId());
        if (StrUtil.isNotBlank(workOrder.getSearchValue())) {
            workOrder.setBusUserId(getUserId());
        }
        return workOrderService.countState(workOrder);
    }

    /**
     * 导出工单列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:export')")
    @Log(title = "工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @TenantScope
    public void export(HttpServletResponse response, WorkOrder workOrder) {
        workOrder.setTenantId(TenantContext.getTenantId());
        if (StrUtil.isNotBlank(workOrder.getSearchValue())) {
            workOrder.setBusUserId(getUserId());
        }
        List<WorkOrder> list = workOrderService.exportSelectWorkOrderList(workOrder);
        ExcelUtil<WorkOrder> util = new ExcelUtil<WorkOrder>(WorkOrder.class);
        util.exportExcel(response, list, "工单");
    }

    /**
     * 获取工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:query')")
    @GetMapping(value = "/{workOrderId}")
    public AjaxResult getInfo(@PathVariable("workOrderId") String workOrderId) {
        return success(workOrderService.selectWorkOrderByWorkOrderId(workOrderId));
    }

    /**
     * B端小程序--获取工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:query')")
    @GetMapping(value = "/applet/{workOrderId}")
    public AjaxResult appletGetInfo(@PathVariable("workOrderId") String workOrderId) {
        return success(workOrderService.appletSelectWorkOrderByWorkOrderId(workOrderId));
    }

    /**
     * 新增工单
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:add')")
    @Log(title = "工单", businessType = BusinessType.INSERT)
    @PostMapping
    @TenantScope
    @RepeatSubmit
    public AjaxResult add(@RequestBody WorkOrder workOrder) {
        workOrder.setTenantId(TenantContext.getTenantId());
        workOrder.setCreateBy(getUsername());
        workOrder.setOperatorId(getUserId());
        return workOrderService.insertWorkOrder(workOrder, getLoginUser().getBizUser().getPhonenumber());
    }

    /**
     * 修改工单
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:edit')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping
    @TenantScope
    @RepeatSubmit
    public AjaxResult edit(@RequestBody WorkOrder workOrder) {
        return toAjax(workOrderService.updateWorkOrder(workOrder));
    }

    /**
     * 编辑已接单、处理中工单
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:edit')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/beingRepaired")
    @TenantScope
    @RepeatSubmit
    public AjaxResult beingRepaired(@RequestBody WorkOrder workOrder) {
        workOrder.setUpdateBy(getUsername());
        workOrder.setOperatorId(getUserId());
        return workOrderService.beingRepaired(workOrder);
    }

    /**
     * 提交缴费单
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:edit')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/submitPaymentSlip/{workOrderId}")
    @TenantScope
    @RepeatSubmit
    public AjaxResult submitPaymentSlip(@PathVariable("workOrderId") String workOrderId) {
        return workOrderService.submitPaymentSlip(workOrderId);
    }

    /**
     * 修改工单紧急程度
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:edit')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/editUrgencyDegree")
    public AjaxResult editUrgencyDegree(@RequestBody WorkOrder workOrder) {
        workOrder.setUpdateBy(getUsername());
        return workOrderService.editUrgencyDegree(workOrder, getLoginUser().getBizUser().getPhonenumber());
    }

    /**
     * 修改工单上门时间
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:edit')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/editEstimateTime")
    public AjaxResult editEstimateTime(@RequestBody WorkOrder workOrder) {
        workOrder.setUpdateBy(getUsername());
        return workOrderService.editEstimateTime(workOrder, getLoginUser().getBizUser().getPhonenumber());
    }

    /**
     * 驳回工单、作废工单
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizLackAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/reject")
    @TenantScope
    @RepeatSubmit
    public AjaxResult rejectWorkOrder(@RequestBody WorkOrderRecord workOrderRecord) {
        return workOrderService.rejectWorkOrder(workOrderRecord, getUsername(), null);
    }

    /**
     * 派单、改派工单
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizLackAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/dispatch")
    @TenantScope
    @RepeatSubmit
    public AjaxResult dispatchWorkOrder(@RequestBody WorkOrder workOrder) {
        if (StrUtil.isBlank(workOrder.getWorkOrderId()) || workOrder.getBusUserId() == null
            || StrUtil.isBlank(workOrder.getPersonTenantId())) {
            return error("数据异常");
        }
        workOrder.setUpdateBy(getUsername());
        return workOrderService.dispatchWorkOrder(workOrder);
    }

    /**
     * 工单员接单
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizHasAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/received")
    @TenantScope
    @RepeatSubmit
    public AjaxResult receivedWorkOrder(@RequestBody WorkOrderRecord workOrderRecord) {
        return workOrderService.receivedWorkOrder(workOrderRecord, getUserId(), TenantContext.getTenantId());
    }

    /**
     * 工单人员申请拒接、申请作废
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizHasAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/requestRejection")
    @TenantScope
    @RepeatSubmit
    public AjaxResult requestRejectionWorkOrder(@RequestBody WorkOrderRecord workOrderRecord) {
        return workOrderService.requestRejectionWorkOrder(workOrderRecord, getUserId(), TenantContext.getTenantId());
    }

    /**
     * 工单人员撤销拒接申请、作废申请
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizHasAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/revocation/rejection")
    @TenantScope
    @RepeatSubmit
    public AjaxResult revocationRejectionWorkOrder(@RequestBody WorkOrderRecord workOrderRecord) {
        return workOrderService.revocationRejectionWorkOrder(workOrderRecord, getUserId(), TenantContext.getTenantId());
    }

    /**
     * 审核拒接、作废
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit')," +
            "@ss.bizLackAnyRoles('maintenance,housekeeper,attendant,cleaner')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/auditDenial")
    @TenantScope
    @RepeatSubmit
    public AjaxResult auditDenialWorkOrder(@RequestBody WorkOrderRecord workOrderRecord) {
        return workOrderService.auditDenialWorkOrder(workOrderRecord, getUsername());
    }

    /**
     * 创建收款码
     *
     * @param workOrderId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:createPayPicture')")
    @GetMapping("/createPayPicture/{workOrderId}")
    @TenantScope
    public AjaxResult createPayPicture(@PathVariable("workOrderId") String workOrderId) {
        return workOrderService.createPayPicture(workOrderId);
    }

    /**
     * 新增跟进记录
     *
     * @param workOrderRecord
     * @return
     */
    @PostMapping("/addWorkOrderRecord")
    @TenantScope
    public AjaxResult addWorkOrderRecord(@RequestBody @Valid WorkOrderRecord workOrderRecord) {
        String recordContent = workOrderRecord.getRecordContent();
        if (StrUtil.isBlank(recordContent)) {
            return error("记录内容不能为空");
        }
        BizUserBusiness bizUser = getLoginUser().getBizUser();
        String username = bizUser.getUserName();
        String phonenumber = bizUser.getPhonenumber();
        workOrderRecord.setRecordContent(username + phonenumber + "新增了记录：" + recordContent);
        workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_ALL_VISIBLE);
        return toAjax(workOrderRecordService.insertWorkOrderRecord(workOrderRecord));
    }


    /**
     * 查询工单跟进记录列表
     */
    @GetMapping("/record/list")
    @TenantScope
    public AjaxResult list(WorkOrderRecord workOrderRecord) {
        String workOrderId = workOrderRecord.getWorkOrderId();
        if (StrUtil.isBlank(workOrderId)) {
            throw new ServiceException("工单ID不能为空");
        }
        List<WorkOrderRecord> list = workOrderRecordService.selectWorkOrderRecordList(workOrderRecord);
        return success(list);
    }



    /**
     * 上传缴费凭证
     *
     * @param workOrder
     * @return
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:addPaymentDocument')," +
            "@ss.bizLackAnyRoles('maintenance,cleaner')}")
    @PostMapping("/addPaymentDocument")
    @TenantScope
    @RepeatSubmit
    public AjaxResult addPaymentDocument(@RequestBody WorkOrder workOrder) {
        String workOrderId = workOrder.getWorkOrderId();
        WorkOrder workOrder1 = workOrderService.selectWorkOrderByWorkOrderId(workOrderId);
        if (workOrder1 == null) {
            throw new ServiceException("工单不存在");
        }
        if (!WorkOrderConstants.WORK_ORDER_STATE_WAIT_PAY.equals(workOrder1.getWorkOrderState())){
            throw new ServiceException("工单状态不正确");
        }

        String paymentDocument = workOrder.getPaymentDocument();
        if (StrUtil.isBlank(paymentDocument)) {
            throw new ServiceException("请上传缴费凭证");
        }
        workOrder1.setPaymentDocument(paymentDocument);
        String recordContent = getUsername() + "上传了缴费凭证";
        WorkOrderRecord workOrderRecord = new WorkOrderRecord(workOrderId, WorkOrderConstants.RECORD_TYPE_USER_VISIBLE,
                WorkOrderConstants.DISPLAY_TYPE_ORDER_COMPLETED, recordContent, paymentDocument, null, null);
        return workOrderService.addPaymentDocument(workOrder1,workOrderRecord);
    }


    /**
     * 工单管理--查询维修人员待完成工单列表
     */
    @GetMapping("/info/{workOrderPersonId}")
    @TenantScope
    public AjaxResult infoByMaintenance(@PathVariable("workOrderPersonId") Long workOrderPersonId) {
        List<WorkOrder> list = workOrderService.selectPendingWorkOrderList(workOrderPersonId);
        return success(list);
    }


    /**
     * 工单管理--工单申请临时密码
     */
    @PreAuthorize("@ss.hasPermi('enterprise:workOrder:applyTemporaryPassword')")
    @GetMapping("/applyTemporaryPassword/{workOrderId}")
    @TenantScope
    @RepeatSubmit
    public AjaxResult applyTemporaryPassword(@PathVariable("workOrderId") String workOrderId) {
        return workOrderService.applyTemporaryPassword(workOrderId, getUsername(),getLoginUser().getBizUser().getPhonenumber(),getUserId());
    }

    /**
     * 工单人员--确认看房
     */
    @PreAuthorize("{@ss.hasPermi('enterprise:workOrder:edit'),@ss.bizHasAnyRoles('housekeeper,attendant')}")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PutMapping("/confirm/lookHouse")
    @TenantScope
    @RepeatSubmit
    public AjaxResult confirmLookHouseWorkOrder(@RequestBody WorkOrder workOrder) {
        workOrder.setUpdateBy(getUsername());
        workOrder.setOperatorId(getUserId());
        return workOrderService.confirmLookHouseWorkOrder(workOrder, getUserId(), TenantContext.getTenantId());
    }
}
